<template>
  <div v-if="available">
    <el-container>
      <el-main style="overflow-y: hidden" class="main-background">
        <!-- 问卷主体区域 -->
        <el-card class="main-area">
          <el-progress
            :percentage="
              Number(
                (questionnaire.total / questionnaire.questions.length) * 100
              )
            "
            :show-text="false"
          ></el-progress>
          <!-- 问卷时间 -->
          <div
            class="timer"
            v-if="questionnaire.type == 'exam' && questionnaire.end_time"
          >
            <span
              >{{ PrefixInteger(lefttime.hour, 2) }} :
              {{ PrefixInteger(lefttime.minute, 2) }} :
              {{ PrefixInteger(lefttime.second, 2) }}</span
            >
          </div>
          <!-- 问卷内容部分 -->
          <div class="content-area">
            <div class="name1">
              <span>{{ questionnaire.title }}</span>
            </div>
            <div class="description">
              <span>{{ questionnaire.desc }}</span>
            </div>
            <!-- 问卷问题 -->
            <div
              class="question-area"
              v-for="(question, index) in questionnaire.questions"
              :key="index"
            >
              <single-preview
                v-if="question.type === 'single'"
                :question="question"
                :number="index + 1"
                :changeAnswers="changeAnswers"
                :saveAnswer="saveAnswer"
                :showNumber="questionnaire.show_number"
              ></single-preview>
              <multi-preview
                v-if="question.type === 'multi'"
                :question="question"
                :number="index + 1"
                :changeAnswers="changeAnswers"
                :saveAnswer="saveAnswer"
                :showNumber="questionnaire.show_number"
              ></multi-preview>
              <fill-preview
                v-if="question.type === 'fill'"
                :question="question"
                :number="index + 1"
                :changeAnswers="changeAnswers"
                :saveAnswer="saveAnswer"
                :showNumber="questionnaire.show_number"
              ></fill-preview>
              <grade-preview
                v-if="question.type === 'grade'"
                :question="question"
                :number="index + 1"
                :changeAnswers="changeAnswers"
                :saveAnswer="saveAnswer"
                :showNumber="questionnaire.show_number"
              ></grade-preview>
            </div>
            <!-- 提交按钮 -->
            <div class="commit">
              <el-button
                type="primary"
                class="commit-button"
                @click="commitAnswer"
                >提交</el-button
              >
            </div>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  import axios from "axios";
  import FillPreview from "../components/Preview/FillPreview.vue";
  import GradePreview from "../components/Preview/GradePreview.vue";
  import MultiPreview from "../components/Preview/MultiPreview.vue";
  import SinglePreview from "../components/Preview/SinglePreview.vue";
  export default {
    components: { SinglePreview, MultiPreview, FillPreview, GradePreview },
    data() {
      return {
        questionnaire: {
          title: "",
          desc: "",
          total: 0,
          questions: [],
          type: null,
        },
        questionnaire_id: null,
        available: false,
        timer: null,
        submitId: null,
        ip: null,
        seconds: 0,
        timerForSubmit: null,
        continue: false,
        done: false,
        time_not_exceed: true,
        timer_exceed: null,
        endtime: null,
        timer2: null,
        endList: [],
        timer3: null,
        timer4: null,
        to: null,
        lefttime: {
          hour: 60,
          minute: 60,
          second: 60,
        },
        // answer
      };
    },
    async created() {
      this.ip = localStorage.getItem("Ip");
      this.questionnaire_id = this.$route.params.id;
      this.to = this.$route.params.id;
      await axios
        .post("decode/", {
          questionnaire_id: this.questionnaire_id,
        })
        .then((response) => {
          if (response.data.code == -1) {
            this.$router.push({
              path: "/failure",
              query: {
                msg: "该问卷不存在或您没有权限访问",
              },
            });
          }
          this.questionnaire_id = response.data.id;
        });
      await this.getQuestionnaire();
      // 1.先确定问卷是否设置了乱序
      // 2.判断用户是否填过问卷
      // 3.若填过 存储问题顺序.否则获取顺序并随机化
      // clearTimeout(this.timer3);
      // this.timer3 = setTimeout(() => {
      if (this.questionnaire.is_out_of_order) {
        const formData = {
          questionnaire_id: this.questionnaire_id,
          ip: this.ip,
        };
        await axios.post("check/", formData).then((response) => {
          console.log("结果");
          console.log(response.data.code);
          if (
            response.data.code == -8 &&
            localStorage.getItem("order" + this.ip + this.questionnaire_id)
          ) {
            console.log("填过");
            console.log(
              localStorage.getItem("order" + this.ip + this.questionnaire_id)
            );
            var order = JSON.parse(
              localStorage.getItem("order" + this.ip + this.questionnaire_id)
            );
            var tmp = this.questionnaire.questions;
            this.questionnaire.questions.sort(function (a, b) {
              var index1 = order.indexOf(tmp.indexOf(a));
              var index2 = order.indexOf(tmp.indexOf(b));
              return index1 < index2 ? -1 : 1;
            });
          } else if (response.data.code == 0) {
            console.log("没填过");
            // 没填过，存个随机顺序
            var length = this.questionnaire.questions.length;
            var order1 = [];
            for (var i = 0; i < length; i++) {
              order1.push(i);
            }
            console.log(this.questionnaire);
            console.log(order1);
            order1.sort(function () {
              return 0.5 - Math.random();
            });
            console.log(order1);
            if (this.questionnaire.type == "exam") {
              var position0 = order1.indexOf(0);
              var temp1;

              temp1 = order1[0];
              order1[0] = 0;
              order1[position0] = temp1;

              var position1 = order1.indexOf(1);
              temp1 = order1[1];
              order1[1] = 1;
              order1[position1] = temp1;
            }
            console.log(order1);
            console.log("束手就擒吧");
            console.log(this.questionnaire);
            var temp = this.questionnaire.questions;
            this.questionnaire.questions.sort(function (a, b) {
              var index1 = order1.indexOf(temp.indexOf(a));
              var index2 = order1.indexOf(temp.indexOf(b));
              return index1 < index2 ? -1 : 1;
            });
            localStorage.setItem(
              "order" + this.ip + this.questionnaire_id,
              JSON.stringify(order1)
            );
          } else if (response.data.code == -9) {
            this.$router.push({
              path: "/failure",
              query: {
                msg: "问卷达到最大填写人数，打开失败",
              },
            });
          } else {
            this.$router.push({
              path: "/failure",
              query: {
                msg: response.data.msg,
              },
            });
          }
        });
      }
      // }, 300);
      // clearTimeout(this.timer3);
      // this.timer3 = setTimeout(() => {
      const formData = {
        questionnaire_id: this.questionnaire_id,
        ip: this.ip,
      };
      await axios.post("check/", formData).then((response) => {
        console.log("进check");
        var code = response.data.code;
        console.log("code");
        console.log(code);
        if (code == 0) {
          this.available = true;
          this.timerForSubmit = setInterval(this.addSeconds, 1000);
        } else if (code == -9) {
          this.$router.push({
            path: "/failure",
            query: {
              msg: "问卷达到最大填写人数，打开失败",
            },
          });
        } else if (code == -8) {
          // 这个人问卷填了一半
          // 让他继续填
          this.continue = true;
          this.timerForSubmit = setInterval(this.addSeconds, 1000);
          console.log("continue1");
          console.log(this.continue);
        } else {
          this.$router.push({
            path: "/failure",
            query: {
              msg: response.data.msg,
            },
          });
        }
        console.log("第二个结束");
      });
      await axios
        .post("answer_preview/", { questionnaire_id: this.questionnaire_id })
        .then((response) => {
          console.log("response");
          console.log(response.data);
          this.endtime = response.data.end_time;
        });

      // 获取填一半的问卷信息并赋值给本地问卷
      console.log("第二个开始");
      if (this.continue) {
        await axios.post("getanswer/", formData).then((response) => {
          console.log("伏法认罪吧！");
          console.log(response.data);
          for (var i = 0; i < response.data.questions.length; i++) {
            for (var j = 0; j < this.questionnaire.questions.length; j++) {
              console.log("i" + i);
              console.log("j" + j);
              // console.log()
              if (
                this.questionnaire.questions[j].id ==
                response.data.questions[i].id
              ) {
                console.log("感兴趣的");
                console.log(this.questionnaire.questions);
                var temp = this.questionnaire.questions[j];
                var data = response.data.questions[i];
                if (temp.type == "multi" || temp.type == "single") {
                  this.questionnaire.questions[j]["answer"] = data.options;
                } else if (temp.type == "grade") {
                  this.questionnaire.questions[j]["grade"] = data.answer;
                } else {
                  this.questionnaire.questions[j]["fill"] = data.text;
                  console.log("text");
                  console.log(data.text);
                }
              }
            }
          }
          console.log("看看你错在哪里！");
          console.log(this.questionnaire.questions);
          this.available = true;
        });
      }
      if (this.endtime) {
        // clearTimeout(this.timer2);
        // this.timer2 = setTimeout(() => {
        var d = this.endtime.substring(0, 10).split("-");
        var t = this.endtime.substring(11, 19).split(":");
        for (var i = 0; i < d.length; i++) {
          this.endList.push(Number(d[i]));
        }
        for (var j = 0; j < t.length; j++) {
          this.endList.push(Number(t[j]));
        }
        this.getTime();
        // }, 300);
      }
      if (this.endtime) {
        var time = this.endtime.substring(11, 19).split(":");
        var endtime =
          3600 * Number(time[0]) + 60 * Number(time[1]) + Number(time[2]);
        var now = new Date();
        var starttime =
          3600 * now.getHours() + 60 * now.getMinutes() + now.getSeconds();
        console.log("yes");
        console.log(time);
        console.log(now);
        var minus = endtime - starttime;
        if (minus > 0) {
          this.lefttime.hour = Math.floor(minus / 3600);
          this.lefttime.minute = Math.floor((minus % 3600) / 60);
          this.lefttime.second =
            minus - 3600 * this.lefttime.hour - 60 * this.lefttime.minute;
          console.log(this.lefttime.hour);
          console.log(this.lefttime.minute);
          console.log(this.lefttime.second);
          clearTimeout(this.timer2);
          this.timer2 = setInterval(() => {
            this.lefttime.second -= 1;
            if (this.lefttime.second < 0) {
              this.lefttime.second = 59;
              this.lefttime.minute -= 1;
              if (this.lefttime.minute < 0) {
                this.lefttime.minute = 59;
                this.lefttime.hour -= 1;
                if (this.lefttime.hour < 0) {
                  this.lefttime.hour = 0;
                  this.lefttime.minute = 0;
                  this.lefttime.second = 0;
                  clearInterval(this.timer2);
                }
              }
            }
          }, 1000);
        }
      }
    },
    beforeUnmount() {
      this.timer = null;
      this.timerForSubmit = null;
      this.timer_exceed = null;
      this.timer2 = null;
    },
    methods: {
      PrefixInteger(num, length) {
        return (num / Math.pow(10, length)).toFixed(length).substr(2);
      },
      addSeconds() {
        this.seconds += 1;
      },
      getTime() {
        clearTimeout();
        this.timer_exceed = setInterval(() => {
          var time = new Date();
          var timeList = [];
          timeList.push(time.getFullYear());
          timeList.push(time.getMonth() + 1);
          timeList.push(time.getDate());
          timeList.push(time.getHours());
          timeList.push(time.getMinutes());
          timeList.push(time.getSeconds());
          // 如果超时
          for (var i = 0; i < timeList.length; i++) {
            if (timeList[i] < this.endList[i]) {
              break;
            } else if (timeList[i] == this.endList[i]) {
              continue;
            } else {
              this.time_not_exceed = false;
              clearInterval(this.timer_exceed);
              this.commitAnswer();
              this.timer_exceed = null;
              return;
            }
          }
        }, 1000);
      },
      async commitAnswer() {
        console.log(this.questionnaire.questions);
        if (this.time_not_exceed) {
          // 先判断是不是所有答案都填了
          // 如果没有 则提示没填的题
          var uncompleted = [];
          for (var i = 0; i < this.questionnaire.questions.length; i++) {
            if (
              !(
                (this.questionnaire.questions[i].answer &&
                  this.questionnaire.questions[i].answer.length) ||
                this.questionnaire.questions[i].grade ||
                this.questionnaire.questions[i].fill
              )
            ) {
              if (this.questionnaire.questions[i].must) {
                uncompleted.push(i + 1);
              }
            }
          }
          // 还有题没填写 提示后返回
          if (uncompleted && uncompleted.length) {
            var s = "您还有第";
            for (var j = 0; j < uncompleted.length; j++) {
              s += uncompleted[j] + " ";
            }
            s += "题未填写";
            alert(s);
            return;
          }
          // 判断是否选了已经选满的
          // for(var i = 0; i < this.questionnaire.questions.length; i++) {
          //   // 对于每一个question 对所有选项做遍历
          //   // 如果answer
          // }
        }

        // 向后端发起提交请求
        const formData = {
          id: this.submitId,
          use_time: this.seconds,
          username: localStorage.getItem("username"),
        };
        await axios.post("submit/", formData).then((response) => {
          console.log(response.data);
          if (response.data.code == -1) {
            alert("提交失败，请改动选项后重试");
          } else if (response.data.code == -2) {
            alert("问卷达到最大填写人数，提交失败");
          } else if (response.data.code == -3) {
            alert("您选择了剩余数量为0的选项，提交失败");
          } else if (this.questionnaire.type == "vote") {
            this.$router.push("/voteresult/" + this.to);
          } else if (this.questionnaire.type == "exam") {
            // this.$router.push("/examresualt/")
            this.$router.push({
              path: "/examresult",
              query: {
                questionnaire_id: this.to,
                submitId: this.submitId,
                ip: this.ip,
              },
            });
          } else {
            this.$router.push("/successcommit/" + this.to);
            // this.$router.push("/voteresult/" + this.to)
          }
        });
      },
      async saveAnswer() {
        // 如果用户更改了题目答案
        // 就把当前填过的所有题目的答案传回去

        // 1.构造表格数据
        const formData = {
          id: this.questionnaire_id,
          questionnaire_id: this.questionnaire_id,
          ip: this.ip,
          questions: [],
        };
        for (var i = 0; i < this.questionnaire.questions.length; i++) {
          if (
            this.questionnaire.questions[i].answer &&
            this.questionnaire.questions[i].answer.length
          ) {
            formData.questions.push({
              id: this.questionnaire.questions[i].id,
              type: this.questionnaire.questions[i].type,
              options: this.questionnaire.questions[i].answer,
            });
          } else if (this.questionnaire.questions[i].grade) {
            formData.questions.push({
              id: this.questionnaire.questions[i].id,
              type: this.questionnaire.questions[i].type,
              answer: this.questionnaire.questions[i].grade,
            });
          } else if (this.questionnaire.questions[i].fill) {
            formData.questions.push({
              id: this.questionnaire.questions[i].id,
              type: this.questionnaire.questions[i].type,
              text: this.questionnaire.questions[i].fill,
            });
          }
        }
        // 2.给后端数据并获取submitId
        // clearTimeout(this.timer);
        // this.timer = setTimeout(() => {
        await axios.post("answer/", formData).then((response) => {
          console.log("这是传给后端的保存的答案");
          console.log(formData);
          this.submitId = response.data.id;
        });
        // }, 200);
      },
      async getQuestionnaire() {
        // 获取问卷列表
        console.log("id");
        console.log(this.questionnaire_id);
        const formData = {
          questionnaire_id: this.questionnaire_id,
        };
        await axios.post("preview/", formData).then((response) => {
          this.questionnaire = response.data;
          console.log("后端传过来的问卷");
          console.log(this.questionnaire);
        });
      },
      // 当子组件改变已填写的答案时调用
      // 实时增删改问题列表中的答案
      // index: 题号
      // answer: 新的答案
      changeAnswers(index, answer) {
        if (typeof answer === "object") {
          this.questionnaire.questions[index - 1]["answer"] = [];
          for (var i = 0; i < answer.length; i++) {
            this.questionnaire.questions[index - 1]["answer"].push({
              option_id: answer[i],
            });
          }
        } else if (typeof answer === "number") {
          this.questionnaire.questions[index - 1]["grade"] = answer;
        } else {
          this.questionnaire.questions[index - 1]["fill"] = answer;
        }
      },
      close() {
        this.$router.push("/questionnaire/" + this.to);
      },
    },
    watch: {
      questionnaire: {
        handler: function () {
          console.log("本地问卷");
          console.log(this.questionnaire.questions);
          var count = 0;
          for (var i = 0; i < this.questionnaire.questions.length; i++) {
            // console.log(this.questionnaire.questions[i].answer)
            if (
              (this.questionnaire.questions[i].answer &&
                this.questionnaire.questions[i].answer.length) ||
              this.questionnaire.questions[i].grade ||
              this.questionnaire.questions[i].fill
            ) {
              count += 1;
            }
          }
          this.questionnaire.total = count;
        },
        deep: true,
      },
    },
  };
</script>

<style scoped>
.el-header {
  --el-header-padding: 0;
}

.el-main {
  --el-main-padding: 160px 220px 160px 220px;
  height: 100%;
}

.main-area {
  height: 100%;
}

.name1 {
  display: flex;
  justify-content: center;
  font-family: "微软雅黑";
  font-size: 30px;
}

.description {
  margin-top: 40px;
  font-size: 16px;
}

.content-area {
  margin: 40px;
  font-family: "微软雅黑";
}

.commit {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.commit-button {
  width: 220px;
  height: 40px;
}

.question-area {
  margin-top: 45px;
}

.buttons-header {
  display: flex;
  justify-content: space-between;
}

.buttons {
  margin-top: 10px;
  margin-right: 20px;
}

.el-card {
  opacity: 0.9;
}

.el-container {
  background-image: url(../assets/img2.jpg);
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: 100% 100%;
}

.timer {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  font-family: "微软雅黑";
  font-size: 20px;
}
</style>